package ssq.gamest.wolfmankill;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.Arrays;

import net.sf.json.JSONObject;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import ssq.utils.Base64Utils;
import ssq.utils.LogUtils;
import ssq.utils.message_quene.MessageQuene;
import ssq.gamest.wolfmankill.port_android.MainActivity; //#ifdef Android
//\\import ssq.gamest.wolfmankill.port_windows.MainActivity; //#ifdef Java

public class WSClient extends WebSocketClient {
  private Participant me;
  public MessageQuene messageQuene = new MessageQuene("msg");
  public boolean canVote = false;
  static WSClient instance;
  MainActivity gui = MainActivity.getInstance();

  public static final String CLOSED = "closed";
  public static final String ERROR = "error";
  public static final String RESET = "reset";
  public static final String DISABLE_RECONNECT = "disableReconnect";

  protected static WSClient getInstance() {
    return instance;
  }

  public WSClient(URI serverUri, String name) {
    super(serverUri);

    me = new Participant(name);
    instance = this;

    messageQuene.register(MainActivity.getInstance());
  }

  @Override
  public void onClose(int arg0, String arg1, boolean arg2) {
    messageQuene.offer(JSONObject.fromObject(WSServer.constructMessage(CLOSED, "")));
  }

  @Override
  public void onError(Exception arg0) {
    messageQuene.offer(JSONObject.fromObject(WSServer.constructMessage(ERROR, arg0.getLocalizedMessage())));
  }

  @Override
  public void onMessage(String msg) {
    messageQuene.offer(JSONObject.fromObject(msg));
  }

  @Override
  public void onOpen(ServerHandshake arg0) {
    register();
    messageQuene.offer(JSONObject.fromObject(WSServer.constructMessage(RESET, "")));
    messageQuene.offer(JSONObject.fromObject(WSServer.constructMessage(DISABLE_RECONNECT, "")));
  }

  private void register() {
    send(WSServer.constructMessage("register", getMe().name));
  }

  public String toDetailedString() {
    StringBuilder sb = new StringBuilder(getMe().toFullString());
    sb.append("\n canVote: ").append(canVote);
    return null;
  }

  public Participant getMe() {
    return me;
  }

  public void dispatch(String msg) {
    LogUtils.logString(msg, "dispatching", true);

    JSONObject json;
    try {
      json = JSONObject.fromObject(msg);
    } catch (Exception e1) {
      return;
    }
    String type = "";
    try {
      type = json.getString("type");
    } catch (Exception e) {
    }

    msg = "";
    try {
      msg = json.getString("msg");
    } catch (Exception e) {
    }

    String from = "";
    try {
      from = json.getString("from");
    } catch (Exception e) {
    }

    if (type.equals("msg")) {
      try {
        gui.appendMessage(from + " : " + new String(Base64Utils.decode(msg), "UTF-8"));
      } catch (UnsupportedEncodingException e) {
      }
    } else if (type.equals("fromJson")) {
      try {
        JSONObject tmp = json.getJSONObject("msg");
        me.fromJson(tmp);
        gui.refreshState();
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (type.equals("players")) {
      gui.setNames(Arrays.asList(msg.replace("[", "").replace("]", "").split(",")));
    } else if (type.equals("toggleVote")) {
      canVote = !canVote;
    } else if (type.equals(WSClient.ERROR)) {
      gui.info(msg);
      gui.clearLogin();
    } else if (type.equals(WSClient.CLOSED)) {
      gui.appendMessage("链接已经断开");
      gui.enableReconnect();
    } else {
      try {
        MainActivity.class.getMethod(type, String.class).invoke(gui, msg);
      } catch (Exception e) {
        try {
          MainActivity.class.getMethod(type).invoke(gui);
        } catch (Exception e2) {
          e.printStackTrace();
          LogUtils.logString(e.toString(), "invoke", false);
        }
      }
    }
  }
}
